﻿using AutoMapper;
using PagedList;
using SIG.Infrastructure.Configs;
using SIG.Infrastructure.Helper;
using SIG.InputModel.Admin.Teams;

using SIG.ViewModel;
using SIG.ViewModel.Admin.Teams;
using SIG.WebMVC.Filters;
using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Xml.Linq;
using System.Linq;
using SIG.Resources.Admin;
using SIG.DAL.Dapper.Repositories;
using SIG.DAL.Dapper.Model;

namespace SIG.WebMVC.Areas.Admin.Controllers
{
    [SIGAuth]
    public class TeamController : BaseController
    {
        private readonly TeamRepository _teamService;
        private readonly PageMetaRepository _pageMetaService;
        private readonly IMapper _mapper;

        public TeamController(IMapper mapper)
        {
            _teamService = new TeamRepository();
            _pageMetaService = new PageMetaRepository();
            _mapper = mapper;

        }
        // GET: Admin/Team

        #region Team

        public ActionResult Index(int? page, string keyword)
        {
            TeamListVM teamListVM = GetElements(page, keyword);
         
            ViewBag.PageSizes = new SelectList(Site.PageSizes());
            return View(teamListVM);

        }

        private TeamListVM GetElements(int? page, string keyword)
        {
            var teamListVM = new TeamListVM();

            teamListVM.Keyword = keyword;
            teamListVM.PageIndex = page ?? 1;
            teamListVM.PageSize = SettingsManager.Team.PageSize;
            int totalCount;
            var teamlist = _teamService.GetListPagedItems(teamListVM.PageIndex, teamListVM.PageSize, teamListVM.Keyword, out totalCount);
           // var teamVMList = _mapper.Map<List<Team>, List<TeamVM>>(teamlist);
            teamListVM.TotalCount = totalCount;
            teamListVM.Teams = new StaticPagedList<SIG.DAL.Dapper.Model.Team>(teamlist, teamListVM.PageIndex, teamListVM.PageSize, teamListVM.TotalCount); ;
            return teamListVM;
        }


        [HttpPost]
        public JsonResult PageSizeSet(int pageSize)
        {
            try
            {
                var xmlFile = Server.MapPath("~/Config/TeamSettings.config");
                XDocument doc = XDocument.Load(xmlFile);

                var item = doc.Descendants("Settings").FirstOrDefault();
                item.Element("PageSize").SetValue(pageSize);
                doc.Save(xmlFile);

                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }


        [HttpGet]
        public ActionResult Add()
        {
            var vTeam = new TeamIM();
            vTeam.Active = true;
          

            return PartialView("_Add", vTeam);
        }



        [HttpPost]
        public JsonResult Add(TeamIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            var team = _mapper.Map<TeamIM, Team>(vm);
            team.CreatedBy = Site.CurrentUserName;
            team.CreatedDate = DateTime.Now;
            _teamService.Create(team);

            var pageMeta = new PageMeta()
            {
                ObjectId = team.Id.ToString(),
                Title = string.IsNullOrEmpty(vm.Title) ? vm.Name : vm.Title,
                Keyword = string.IsNullOrEmpty(vm.Keywords) ? string.Empty : vm.Keywords.Replace('，', ','),                
                Description = vm.SEODescription,
                ModelType = (short)ModelType.TEAM
            };
                _pageMetaService.Create(pageMeta);
         

            int count;
            int pageSize = SettingsManager.Team.PageSize;
            var list = _teamService.GetListPagedItems(1, pageSize, string.Empty,out count);
           // List<TeamVM> teamList = _mapper.Map<List<Team>, List<TeamVM>>(list);
            AR.Data = RenderPartialViewToString("_TeamList", list);

            AR.SetSuccess(String.Format(Messages.AlertCreateSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpGet]
        public ActionResult Edit(int id)
        {

            Team team = _teamService.GetById(id);
            if (team == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.AllowGet);
            }

            var vm = _mapper.Map<TeamIM>(team);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.TEAM, team.Id.ToString());
            if (pageMeta != null)
            {
                vm.Title = pageMeta.Title;
                vm.Keywords = pageMeta.Keyword;
                vm.SEODescription = pageMeta.Description;
            }

            return PartialView("_Edit", vm);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]

        public JsonResult Edit(TeamIM vm)
        {

            if (!ModelState.IsValid)
            {
                AR.Setfailure(GetModelErrorMessage());
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            var team = _teamService.GetById(vm.Id);

            team.Importance = vm.Importance;
            team.Name = vm.Name;
            team.PhotoUrl = vm.PhotoUrl;
            team.Post = vm.Post;
            team.Description = vm.Description;
            team.Active = vm.Active;
            team.UpdatedBy = Site.CurrentUserName;
            team.UpdatedDate = DateTime.Now;

            _teamService.Update(team);

            var pageMeta = _pageMetaService.GetPageMeta(ModelType.JOB, vm.Id.ToString());
            pageMeta = pageMeta ?? new PageMeta();

         

                pageMeta.ObjectId = vm.Id.ToString();
            pageMeta.Title = string.IsNullOrEmpty(vm.Title) ? vm.Name : vm.Title;
            pageMeta.Keyword = string.IsNullOrEmpty(vm.Keywords) ? string.Empty : vm.Keywords.Replace('，', ',');       
                pageMeta.Description = vm.SEODescription;
                pageMeta.ModelType = (short)ModelType.TEAM;

                if (pageMeta.Id > 0)
                {
                    _pageMetaService.Update(pageMeta);
                }
                else
                {
                    _pageMetaService.Create(pageMeta);
                }
        


            //var teamVM = _mapper.Map<TeamVM>(team);

            AR.Id = team.Id;
            AR.Data = RenderPartialViewToString("_TeamItem", team);

            AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }

        // DELETE: /User/DeleteSite
        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Delete(int id)
        {

            Team vTeam = _teamService.GetById(id);
                     

            _teamService.Delete(vTeam);
            AR.SetSuccess(String.Format(Messages.AlertDeleteSuccess, EntityNames.Team));
            return Json(AR, JsonRequestBehavior.DenyGet);

        }


        [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult IsActive(int id)
        {

            var vTeam = _teamService.GetById(id);
            if (vTeam == null)
            {
                AR.Setfailure(Messages.HttpNotFound);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }

            try
            {
                vTeam.Active = !vTeam.Active;
                _teamService.Update(vTeam);
               // var vm = _mapper.Map<TeamVM>(vTeam);

                AR.Data = RenderPartialViewToString("_TeamItem", vTeam);
                AR.SetSuccess(String.Format(Messages.AlertUpdateSuccess, EntityNames.Team));
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
            catch (Exception ex)
            {
                AR.Setfailure(ex.Message);
                return Json(AR, JsonRequestBehavior.DenyGet);
            }
        }

        
        


        #endregion
    }
}